package com.springboot.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.springboot.mall.common.Constant;
import com.springboot.mall.exception.MallException;
import com.springboot.mall.exception.MallExceptionEnum;
import com.springboot.mall.model.entity.Product;
import com.springboot.mall.model.mappers.CategoryMapper;
import com.springboot.mall.model.mappers.ProductMapper;
import com.springboot.mall.model.query.ProductListQuery;
import com.springboot.mall.model.request.AddProductRequest;
import com.springboot.mall.model.request.ProductListRequset;
import com.springboot.mall.model.request.UpdateCategoryRequest;
import com.springboot.mall.model.request.UpdateProductRequest;
import com.springboot.mall.model.vo.CategoryVO;
import com.springboot.mall.service.CategoryServcice;
import com.springboot.mall.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/*
 *
 *
 *@data 2022-05-12
 */

@Service("productService")
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryServcice categoryServcice;

    @Override
    public void addProduct(AddProductRequest addProductRequest) {
        Product product = new Product();
        BeanUtils.copyProperties(addProductRequest,product);
        //检测是否重名（根据名字查找）
        Product productOld = productMapper.selectByName(product.getName());
        if (productOld != null){
            throw new MallException(MallExceptionEnum.NAME_EXISTED);
        }
        int count = productMapper.insertSelective(product);
        if (count == 0){
            throw new MallException(MallExceptionEnum.CREATE_FAILED);
        }
    }

    @Override
    public void updateProduct(UpdateProductRequest updateProductRequest) {
        Product product = new Product();
        BeanUtils.copyProperties(updateProductRequest,product);

        if (updateProductRequest.getName() != null){
            //首先判断 更新的名字是否在数据库中已经存在（名字不能重复）
            Product productOld = productMapper.selectByName(updateProductRequest.getName());
            //这里的更新逻辑需要捋一下
            //如果不为空，则数据库已经存在该名字，但是如果知识想更新这个名字的层级，则必然是可以查到这条数据的
            //所以需要验证这条数据的id和传过来的id是否一致
            if(productOld!= null && !productOld.getId().equals(updateProductRequest.getId())){
                throw new MallException(MallExceptionEnum.NAME_EXISTED);
            }
            int i = productMapper.updateByPrimaryKeySelective(product);
            if (i == 0){
                throw new MallException(MallExceptionEnum.UPDATE_FAILED);
            }

        }

    }

    @Override
    public void deleteProduct(Integer id) {
        Product productOld = productMapper.selectByPrimaryKey(id);
        if (productOld == null){
            throw new MallException(MallExceptionEnum.DELETE_FAILED);
        }
        int i = productMapper.deleteByPrimaryKey(id);
        if (i == 0){
            throw new MallException(MallExceptionEnum.DELETE_FAILED);
        }
    }

    @Override
    public void batchUpdateSellStatus(Integer[] ids, Integer sellStatus) {
        productMapper.batchUpdateSellStatus(ids,sellStatus);
    }

    @Override
    public PageInfo listForAdmin(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Product> products = productMapper.selectListForAdmin();
        PageInfo pageInfo = new PageInfo(products);
        return pageInfo;

    }

    @Override
    public Product detail(Integer id) {
        Product product = productMapper.selectByPrimaryKey(id);
        return product ;
    }

    @Override
    public PageInfo list(ProductListRequset productListRequset) {
        ProductListQuery productListQuery = new ProductListQuery();

        //搜搜处理
        if(!StringUtils.isEmpty(productListRequset.getKeyword())) {
            //StringBuffer()合成字符串用的，数据库模糊查找功能
            String keyword = new StringBuffer().append("%").append(productListRequset.getKeyword()).append("%").toString();
            productListQuery.setKeyword(keyword);
        }

        //目录处理：如果查某个目录下的商品，不仅是需要查出来该目录的，还需要查出来子目录的所有商品
        //所以这里要拿到某一个目录id下的所有子目录id的list
        if (productListRequset.getCategoryId() != null){
            List<CategoryVO> categoryVOS = categoryServcice.listForCustomer(productListRequset.getCategoryId());
            ArrayList<Integer> categoryIds = new ArrayList<>();
            categoryIds.add(productListRequset.getCategoryId());
            getCategoryIds(categoryVOS,categoryIds);
            productListQuery.setCategoryIds(categoryIds);
        }

        //排序处理

        String orderBy = productListRequset.getOrderBy();
        if (Constant.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
            PageHelper.startPage(productListRequset.getPageNum(),productListRequset.getPageSize(),orderBy);
        }else{
            PageHelper.startPage(productListRequset.getPageNum(),productListRequset.getPageSize());
        }

        List<Product> productList = productMapper.selectList(productListQuery);
        PageInfo pageInfo = new PageInfo(productList);
        return pageInfo;


    }

    private void getCategoryIds(List<CategoryVO> categoryVOList,ArrayList<Integer> categoryIds){
        for (int i = 0; i <categoryVOList.size(); i++) {
            CategoryVO categoryVO = categoryVOList.get(i);
            if (categoryVO != null){
                categoryIds.add(categoryVO.getId());
                getCategoryIds(categoryVO.getChildCategory(),categoryIds);
            }

        }

    }

}
